﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace Muehle
{
    public class Background : PhoneApplicationPage
    {
        bool _isNewInstance = false;

        public Background()
        {
            _isNewInstance = true;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (_isNewInstance)
            {
                (Application.Current as App).ApplicationDataObjectChanged += new EventHandler(Background_ApplicationDataObjectChanged);

                if ((Application.Current as App).HostName != null) { _updateEverything(); }
                else { (Application.Current as App).GetDataAsynce(); }

            }

            _isNewInstance = false; //allows textboxs to get from memory
        }

        void Background_ApplicationDataObjectChanged(object sender, EventArgs e)
        {
            if (System.Windows.Deployment.Current.Dispatcher.CheckAccess())
                _updateEverything();
            else
            {
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                    { _updateEverything(); }); //the => is like a quick access method...SWEET FIND!
            }
        }

        private void _updateEverything()
        {
            HostName = (Application.Current as App).HostName;
            PortNum = (Application.Current as App).PortNum;
        }

        public static readonly DependencyProperty HostNameDef =
            DependencyProperty.RegisterAttached("HostName", typeof(string), typeof(string), new PropertyMetadata("K9-04"));

        public static readonly DependencyProperty PortNumDef = 
            DependencyProperty.RegisterAttached("PortNum", typeof(int), typeof(int), new PropertyMetadata(1337));

        public string HostName
        {
            get { return (string)GetValue(HostNameDef); }
            set { SetValue(HostNameDef, value); }
        }

        public int PortNum
        {
            get { return (int)GetValue(PortNumDef); }
            set { SetValue(PortNumDef, value); }
        }
    }
}
